package ${package}.controller.sys;

import cn.hutool.core.lang.tree.Tree;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import cn.tannn.jdevelops.annotations.web.authentication.ApiPlatform;
import cn.tannn.jdevelops.annotations.web.constant.PlatformConstant;
import cn.tannn.jdevelops.annotations.web.mapping.PathRestController;
import ${package}.controller.sys.dto.DictionaryAdd;
import ${package}.controller.sys.dto.DictionaryBaseInfo;
import ${package}.controller.sys.dto.DictionaryFixSort;
import ${package}.controller.sys.dto.DictionaryPage;
import ${package}.sys.entity.Dictionary;
import ${package}.sys.service.DictionaryService;
import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.jpa.constant.SQLOperator;
import cn.tannn.jdevelops.jpa.result.JpaPageResult;
import cn.tannn.jdevelops.result.response.ResultPageVO;
import cn.tannn.jdevelops.result.response.ResultVO;
import cn.tannn.jdevelops.utils.core.string.StringNumber;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * 字典表
 * ps 不是所有的类都需要vo接收
 *
 * @author tnnn
 * @version V1.0
 * @date 2024-10-9
 */
@PathRestController("dict")
@Slf4j
@Tag(name = "字典管理")
@RequiredArgsConstructor
public class DictionaryController {

    private final DictionaryService dictionaryService;



    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取详情", description = "info")
    public ResultVO<Dictionary> info(@PathVariable("id") Integer id) {
        Dictionary bean = dictionaryService.findOnly("id", id).orElse(new Dictionary());
        return ResultVO.success(bean);
    }

    @GetMapping("/subLevel/{parentCode}")
    @Operation(summary = "查询单层子级", description = "subLevel")
    public ResultVO<List<Dictionary>> subLevel(@PathVariable("parentCode") String parentCode) {
        return ResultVO.success(dictionaryService.findEfficacious(parentCode));
    }


    @GetMapping("/tree")
    @Operation(summary = "字典树", description = "tree")
    public ResultVO<List<Tree<String>>> tree() {
        return ResultVO.success(dictionaryService.tree());
    }

    @Operation(summary = "新增字典表")
    @PostMapping("append")
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    public ResultVO<String> append(@RequestBody @Valid DictionaryAdd append) {
        if(!StringNumber.isInteger(append.getParentCode())){
            throw new BusinessException("非法的ParentCode");
        }
        dictionaryService.peerUniqueTry(append.getParentCode(), append.getName());
        String code = dictionaryService.nextCode(append.getParentCode());
        dictionaryService.saveOne(append.toDictionary(code));
        return ResultVO.success();
    }

    @Operation(summary = "分页查询")
    @PostMapping("page")
    public ResultPageVO<Dictionary, JpaPageResult<Dictionary>> page(@RequestBody @Valid DictionaryPage page) {
        Page<Dictionary> byBean = dictionaryService.findPage(page, page.getPage());
        JpaPageResult<Dictionary> pageResult = JpaPageResult.toPage(byBean);
        return ResultPageVO.success(pageResult, "查询成功");
    }



    @Operation(summary = "有效集合")
    @GetMapping("lists/efficacious")
    @Parameter(name = "parentCode",description = "父级code,为空查所有,顶级0",required = false)
    public ResultVO<List<Dictionary>> listsEfficacious(@RequestParam(value = "parentCode",required = false) String parentCode) {
        List<Dictionary> finds = dictionaryService.findEfficacious(parentCode);
        return ResultVO.success(finds);
    }

    @Operation(summary = "所有集合")
    @GetMapping("lists")
    @Parameter(name = "parentCode",description = "父级code,为空查所有,顶级0",required = false)
    public ResultVO<List<Dictionary>> lists(@RequestParam(value = "parentCode",required = false) String parentCode ) {
        List<Dictionary> finds = dictionaryService.finds(parentCode);
        return ResultVO.success(finds);
    }

    /**
     * 不支持批量
     */
    @GetMapping("enabled")
    @Operation(summary = "启用字典", description = "启用会启用他的所有子类")
    @ApiOperationSupport(order = 3)
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    public ResultVO<String> enabled(@RequestParam("code") String code) {
        dictionaryService.enable(code);
        return ResultVO.successMessage("启用成功");
    }

    /**
     * 不支持批量
     */
    @GetMapping("disable")
    @Operation(summary = "禁用字典", description = "禁用会禁用他的所有子类，禁用不会干扰原来已经用的字典")
    @ApiOperationSupport(order = 4)
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    public ResultVO<String> disable(@RequestParam("code") String code) {
        dictionaryService.disabled(code);
        return ResultVO.successMessage("禁用成功");
    }



    @Operation(summary = "删除字典(同时删除其全部子级)")
    @DeleteMapping("/delete/{code}")
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    @Parameter(name = "code", description = "code", required = true)
    public ResultVO<String> delete(@PathVariable("code") String code) {
        // 删除子级
        dictionaryService.deleteEq("code",code);
        // 删除子级
        List<Dictionary> subCode = dictionaryService.findLowLevel(code);
        dictionaryService.getJpaBasicsDao().deleteAll(subCode);
        return ResultVO.successMessage("删除成功");
    }


    @Operation(summary = "修改字典基础信息")
    @PostMapping("editBaseInfo")
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    public ResultVO<String> editBaseInfo(@RequestBody @Valid DictionaryBaseInfo edit) {
        Dictionary dictionary
                = dictionaryService.getJpaBasicsDao()
                .findById(edit.getId()).orElseThrow(() -> new BusinessException("请选择正确的字典"));
        edit.toSave(dictionary,dictionaryService);
        return ResultVO.success();
    }

    @Operation(summary = "修改字典排序")
    @PostMapping("fixSort")
    @ApiPlatform(platform = PlatformConstant.WEB_ADMIN)
    public ResultVO<String> fixSort(@RequestBody @Valid List<DictionaryFixSort> edit) {
        edit.forEach(item -> dictionaryService.fixSort(item.getId(), item.getSort()));
        return ResultVO.success();
    }
}
